package com.my.security;

import com.alibaba.druid.util.StringUtils;
import com.my.sys.model.SysResource;
import com.my.sys.service.SysResourceService;
import org.apache.shiro.config.Ini;
import org.springframework.beans.factory.FactoryBean;

import java.text.MessageFormat;
import java.util.Iterator;
import java.util.List;

/**
 * Created by 80002023 on 2016/5/5.
 */
public class ChainDefinitionsMetaSource implements FactoryBean<Ini.Section>{

    //@Autowired
    private SysResourceService iaasResourceService;

    private String filterChainDefinitions;
    /**
     * 默认premission字符串
     */
    public static final String PREMISSION_STRING="perms[\"{0}\"]";

    public Ini.Section getObject() throws Exception {
        //获取所有Resource
        List<SysResource> list = iaasResourceService.findAll();

        Ini ini = new Ini();
        //加载默认的url
        ini.load(filterChainDefinitions);
        Ini.Section section = ini.getSection(Ini.DEFAULT_SECTION_NAME);
        //循环Resource的url,逐个添加到section中。section就是filterChainDefinitionMap,
        //里面的键就是链接URL,值就是存在什么条件才能访问该链接
        for (Iterator<SysResource> it = list.iterator(); it.hasNext();) {

            SysResource resource = it.next();
            //如果不为空值添加到section中
            if(StringUtils.isEmpty(resource.getUrl()) && StringUtils.isEmpty(resource.getStringPermissions())) {
                section.put(resource.getUrl(),  MessageFormat.format(PREMISSION_STRING,resource.getStringPermissions()));
            }

        }

        return section;
    }

    public Class<?> getObjectType() {
        return null;
    }

    public boolean isSingleton() {
        return false;
    }
}
